<?php
namespace Mouta\AmistateBundle\Controller;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\UserEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Mouta\UserBundle\Form\Type\ContactType;
use Mouta\UserBundle\Form\Type\MessageType;
use Symfony\Component\HttpFoundation\Response;
use Mouta\AmistateBundle\Entity\Mensaje;
use Mouta\AmistateBundle\Entity\Denuncia;
use Mouta\AmistateBundle\Form\DenunciaType;
use Mouta\AmistateBundle\Entity\Usuario;


class DefaultController extends Controller
{
    public function registerPanelAction()
    {
		/** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');
		
		$request = $this->getRequest();

        $user = $userManager->createUser();
        $user->setEnabled(true);
		$user->setUsername("temporal");
		$user->setCumple(new \DateTime('01/01/1982'));
		
		$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, new UserEvent($user, $request));

        $form = $formFactory->createForm();
        $form->setData($user);
		
		
		
        return $this->render('AmistateBundle:Default:register_panel.html.twig',array(
			'form' => $form->createView()
		));
    }
	
    public function formSendMessageAction($userTo = null, $callback = 'updateMessage', $mostrarCaptcha = true)
    {
        $limitMsg = 2;
        $session = $this->get('session');
		$request = $this->getRequest();
		$message = new Mensaje();
		if ($request->isMethod('POST')) 
		{
			$idUserTo = $request->get('userTo');
			$userTo = $this->getDoctrine()->getManager()->getRepository('AmistateBundle:Usuario')->find( $idUserTo );
            if($request->get('callback') == 'updateMessage')
            {
                $mostrarCaptcha = false;
            }
		}

        $form = $this->createForm(new MessageType(), $message);
        if( ($session->get('mensajes_enviados',0) < $limitMsg ) || ($mostrarCaptcha == false) ) {
            $form->remove('captcha');
        }

		$user = $this->container->get('security.context')->getToken()->getUser();

		if ($request->isMethod('POST')) 
		{
			$form->bind($request);

			if ($form->isValid()) 
			{
                if((new \DateTime()) > $session->get('hora_posterior'))
                {
                    $session->set('mensajes_enviados',0);
                }

                $session->set('mensajes_enviados',$session->get('mensajes_enviados',0)+1);

                if($session->get('mensajes_enviados') == 1)
                {
                    $session->set('hora_posterior', new \DateTime("+ 1 hour"));
                }

                    $message = $form->getData();
                    $message->setIp($request->getClientIp());
                    $message->setUsuarioFrom($user);
                    $message->setUsuarioTo($userTo);

                    $em = $this->getDoctrine()->getEntityManager();
                    $em->persist($message);
                    $em->flush();

                    if($request->get('callback') == 'reload')
                    {
                        $request->getSession()->getFlashBag()->add('success', 'El mensaje ha sido enviado!');
                    }

                    $response = new Response(json_encode( array('valid'=>true,'message'=>$message,'userId'=>$userTo->getId()) ));

			}
			else
			{
                $dataReturn = array('valid'=>false, 'errors'=>$this->getErrorMessages($form));

                if($form->has('captcha'))
                {
                    $dataReturn['newCaptcha'] = $this->generateUrl('genemu_captcha_refresh').'?'.time();
                }

				$response = new Response(json_encode( $dataReturn ));
			}
			$response->headers->set('Content-Type', 'application/json');
			return $response;
		}

        return $this->render('AmistateBundle:Default:form_send_message.html.twig',array(
			'form' => $form->createView(),
			'callback' => $callback,
			'userTo' => $userTo
		));
    }
	
    public function formDenunciarAction($userInfractor = null, $tipo = null, $extra = null)
    {
		$request = $this->getRequest();
		$denuncia = new Denuncia();
		$anonimUser = false;
		
		if(is_null($userInfractor) && $request->isMethod('POST') && $request->get('userInfractor'))
		{
			$idUserInfractor = $request->get('userInfractor');
			$userInfractor = $this->getDoctrine()->getManager()->getRepository('AmistateBundle:Usuario')->find( $idUserInfractor );
		}
		
		if(is_null($tipo))
		{
			$data = $request->get('mouta_amistatebundle_denuncia');
			$tipo = $data['tipo'];
			$extra = $data['extra'];
		}
		
		if($this->get('security.context')->isGranted('ROLE_USER'))
		{
			$user = $this->container->get('security.context')->getToken()->getUser();
			$denuncia->setDenunciante($user);
		} else {
			$anonimUser = true;
			$denuncia->setDenunciante(new Usuario());
		}
		$denuncia->setTipo($tipo);
		$denuncia->setExtra($extra);
		
		$denuncia->setInfractor($userInfractor);
		
		$form = $this->createForm(new DenunciaType(), $denuncia);
		
		if($request->isMethod('POST') && $request->get('mouta_amistatebundle_denuncia'))
		{
			$form->bind($request);

			if ($form->isValid()) 
			{
				
				$denuncia = $form->getData();
				
				if($anonimUser)
				{
					$denuncia->setDenunciante(null);
				}
				
				$em = $this->getDoctrine()->getEntityManager();
				$em->persist($denuncia);
				$em->flush();
				
				$response = new Response(json_encode( array('valid'=>true)) );
			}
			else
			{
				$response = new Response(json_encode( array('valid'=>false, 'errors'=>$this->getErrorMessages($form)) ));
			}
			$response->headers->set('Content-Type', 'application/json');
			return $response;
		}

        return $this->render('AmistateBundle:Default:formDenunciar.html.twig',array(
			'form' => $form->createView(),
			'userInfractor' => $userInfractor
		));
    }
	
	public function footerAction()
    {
		return $this->render('AmistateBundle:Default:footer.html.twig',array(
		));
	}
	
	public function terminosAction()
    {
		return $this->render('AmistateBundle:Default:terminos.html.twig',array(
		));
	}
	
	public function chatAction()
    {
		$seoPage = $this->container->get('sonata.seo.page');
		$seoPage
			->setTitle('Chat gratis en español, chat con mujeres y hombres')
			->addMeta('name', 'description', 'Tu comunidad de Chats gratis destinada a conocer gente en el Chat Español, mujeres y hombres. Chatear y ligar con contactos de todos los paises y ciudades.')
		;
		
		$nombre = 'Amistate.com-'.time();
		if ($this->get('security.context')->isGranted('ROLE_USER')) 
		{
            $user = $this->get('security.context')->getToken()->getUser();
            $nombre = $nombre = 'Amistate.com-' . $user->getNombre();
        }
		return $this->render('AmistateBundle:Default:chat.html.twig',array(
			'nombre'=> $nombre
		));
	}
	
	public function privacidadAction()
    {
		return $this->render('AmistateBundle:Default:privacidad.html.twig',array(
		));
	}
	
	public function usersInHeaderAction()
    {
		$users = $this->getDoctrine()->getManager()->getRepository('AmistateBundle:Usuario')->findUserAtHeader();
		$usersLeft = array();
		$usersRight = array();
		foreach($users as $key => $user)
		{
			if ($key %2 == 0)
			{
				$usersLeft[] = $user;
			}else{
				$usersRight[] = $user;
			}
		}
		return $this->render('AmistateBundle:Default:usersInHeader.html.twig',array('usersLeft'=>$usersLeft,'usersRight'=>$usersRight));
	}
	
	public function contactenosAction()
    {
		$form = $this->createForm(new ContactType());
		$request = $this->getRequest();
		
		if ($request->isMethod('POST')) {
			$form->bind($request);

			if ($form->isValid()) {
				$message = \Swift_Message::newInstance()
					->setSubject($form->get('subject')->getData())
					->setFrom($form->get('email')->getData())
					->setTo('carlosdanielmou@gmail.com')
					->setContentType('text/html');
				
				$body = $this->renderView(
							'UserBundle:Emails:contact.html.twig',
							array(
								'ip' => $request->getClientIp(),
								'name' => $form->get('name')->getData(),
								'message' => $form->get('message')->getData()
							)
						);
				
				$cid1 = $message->embed(\Swift_Image::fromPath( realpath( __DIR__ . '/../../AmistateBundle/Resources/public/images/logo.png') ) );
				$cid2 = $message->embed(\Swift_Image::fromPath( realpath( __DIR__ . '/../../AmistateBundle/Resources/public/images/like-glyph.png') ) );

				$body = str_replace(array('[[cid1]]','[[cid2]]'), array($cid1,$cid2), $body);
				
				$message->setBody($body);
				
				

				$this->get('mailer')->send($message);

				$request->getSession()->getFlashBag()->add('success', 'El email ha sido enviado! Gracias por contactarnos!');

				return $this->redirect($this->generateUrl('contactenos'));
			}

		}
		
		return $this->render('AmistateBundle:Default:contactenos.html.twig',array('form' => $form->createView()));
	}
	
	private function getErrorMessages(\Symfony\Component\Form\Form $form) {
		$errors = array();

		foreach ($form->getErrors() as $key => $error) {
				$errors[] = $this->get('translator')->trans($error->getMessage());
		}

		foreach ($form->all() as $child) {
			if (!$child->isValid()) {
				$errors[$child->getName()] = $this->getErrorMessages($child);
			}
		}

		return $errors;
	}
}
